// import { UseFetchOptions } from '#app';
// import { useAuthStore } from '~/stores/auth';
// import { StorageSerializers, RemovableRef } from '@vueuse/core';
// HeadersInit
// let d: HeadersInit;
// interface myHeaders extends HeadersInit {
//   token?: string;
//   authorization?: string;
// }
// console.log(useRuntimeConfig());
// import mockApi from '~/mock/api';

// import { $Fetch, createFetch } from 'ofetch';
// console.log($fetch);

let _fetchApi: ReturnType<typeof $fetch.create>;

// 因为自动导入前不能使用useRuntimeConfig()，所以这里写成在第一次请求时创建
const getFetchApi = () =>
  (_fetchApi =
    _fetchApi ||
    $fetch.create({
      baseURL: useRuntimeConfig().public.apiBaseUrl,
      // baseURL: '/api',
      headers: {
        // token: authStore.token || '',
        Authorization: '',
      },
      async onRequest({ request, options }) {
        // console.log(
        //   '🚀 ~ file: useFetchApi.ts:30 ~ onRequest ~ request:',
        //   request,
        // );
        options.headers = <Record<string, string>>(options?.headers || {});
        // console.log($fetch);

        const auth = useAuth();
        // console.log(
        //   '🚀 ~ file: useFetchApi.ts:34 ~ onRequest ~ auth:',
        //   auth.accessToken,
        //   auth.raw,
        //   auth.user,
        //   auth.fetchUser,
        // );
        await auth;
        // console.log(
        //   '🚀 ~ file: useFetchApi.ts:47 ~ onRequest ~ auth:',
        //   auth.accessToken,
        //   auth.raw,
        //   auth.user,
        //   auth.fetchUser,
        // );

        // await useAuth().useUser();
        options.headers.Authorization = auth.accessToken
          ? 'Bearer ' + auth.accessToken
          : '';
        // return false;
        // console.log(JSON.stringify(options.headers));
        // throw new Error('44555');
      },
      async onRequestError({ request, options }) {},
      async onResponse(context) {
        const { request, response, options, error } = context;
        // consola.log([request, response, options, error]);

        if (response.status === 401 && !options.isRefreshToken) {
          // token失效刷新token
          const auth = useAuth();
          await auth;

          const refreshSuccess = await auth.executeRefreshToken().then(
            () => true,
            () => false,
          );

          if (refreshSuccess) {
            // options.retry = 1;
            // 刷新后重新请求
            const res = await getFetchApi().raw(request, {
              ...options,
              isRefreshToken: true,
            });
            context.response = res;
            return;
          }
        }

        // if (response._data?.success) {
        // response._data = response._data.data;
        //   return;
        // }
        // if (options.onResponseError) {
        //   await options.onResponseError(context);
        // }
        // onError()
        // response.status = 400;
        // context.error = new Error(
        //   context.response._data?.message ||
        //     context.response._data?.error ||
        //     '请求错误',
        // );
        // response.ok = false;
        // throw new Error(
        //   response._data?.message || response._data?.error || '请求错误',
        // );
      },
      async onResponseError(context) {
        const { request, response, options, error } = context;
        // consola.log([request, response, options, error]);

        // if (response.status === 401 && !options.isRefreshToken) {
        //   ElMessageBox.confirm('提示', '登录信息已过期，是否重新登录', {
        //     appendTo: '#__nuxt',
        //   }).then(async () => {
        //     await navigateTo({
        //       name: 'signIn',
        //       replace: true,
        //     });
        //     useAuth().reset();
        //   });
        // }

        // if (response.status === 403 && !options.isRefreshToken) {
        //   const auth = useAuth();
        //   await auth;

        //   const refreshSuccess = await auth.executeRefreshToken().then(
        //     () => true,
        //     () => false,
        //   );

        //   if (refreshSuccess) {
        //     options.retry = 1;
        //     const res = await getFetchApi().raw(request, {
        //       ...options,
        //       retry: true,
        //     });
        //     console.log(
        //       '🚀 ~ file: useFetchApi.ts:105 ~ onResponseError ~ res:',
        //       res,
        //     );

        //     context.response = res;

        //     return;
        //   }
        // }

        throw createError({
          statusCode: response.status,
          statusMessage:
            error?.message || response._data?.message || '请求错误',
          // request,
          // response,
          // options,
        });
        // throw (
        //   error ||

        //   // new Error(
        //   //   response._data?.message || response._data?.error || '请求错误',
        //   // )
        // );
      },
    }));

export const $fetchApi = (
  url: Parameters<typeof _fetchApi>[0],
  options?: Parameters<typeof _fetchApi>[1],
) => getFetchApi()(url, options);

export const useFetchApi: typeof useFetch = (request, options) =>
  useFetch(request, {
    ...options,
    $fetch: getFetchApi(),
  });

export const useLazyFetchApi: typeof useLazyFetch = (request, options) =>
  useLazyFetch(request, {
    ...options,
    $fetch: getFetchApi(),
  });
